import { CommonActions, useNavigation } from '@react-navigation/native';
import { useEffect, useState } from 'react';
import { getAvailablePurchases } from 'react-native-iap';
import Toast from 'react-native-toast-message';
import { useDispatch, useSelector } from 'react-redux';

import { t } from 'i18next';
import { debounce } from 'lodash';

import { useBusinessPayment } from './pay/useBusinessPayment';
import { paymentAPI } from '@/api/paymentAPI';
import { notificationKey } from '@/constants';
import { setIsFirstLaunch } from '@/stores/slice/appSlice';
import { setItemPayCode } from '@/stores/slice/displaySlice';
import { setInfo } from '@/stores/slice/userSlice';
import { RootState } from '@/stores/store';
import { getUserMemberInfo, isIOS } from '@/utils';
import { AdjustEventsUtil } from '@/utils/adjust';
// import { FirebaseEvents } from '@/utils/firebaseEvents';
// import {AppsFlyerEvents} from '@/utils/appsflyer';
import eventEmitter from '@/utils/eventManager';
// import PayServer from '@/utils/pay';
import { showToast } from '@/utils/showToast';

const useSubscribe = () => {
  const dispatch = useDispatch();
  const navigation = useNavigation();
  const planList = useSelector((state: RootState) => state.paywall.paywallProductDetailList);
  const [selectedPlanCode, setSelectedPlanCode] = useState('');
  const [isRestoring, setIsRestoring] = useState(false);

  const { handlePayment, isSubscribing } = useBusinessPayment();

  const itemPayCode = useSelector((state: RootState) => state.display.itemPayCode);

  const [payEnable] = useState(true);

  const [member, setMember] = useState(false);

  useEffect(() => {
    getUserMemberInfo().then((res) => {
      dispatch(setInfo(res || null));

      if (res?.status && [3, 4, '3', '4'].includes(res.status)) {
        // 非会员
        setMember(false);
      } else {
        // 是会员
        setMember(true);
      }
    });
  }, []);

  // useEffect(() => {
  //   if (!isFirstLaunch) {
  //     return;
  //   }
  //   // 没显示过弹
  //   const data = true;
  //   dispatch(setShowGoEvaluate(data));
  // }, []);

  useEffect(() => {
    const listener = () => {
      doNext();
    };
    eventEmitter.on(notificationKey.pay_success, listener);
    return () => {
      eventEmitter.removeListener(notificationKey.pay_success, listener);
    };
  }, []);

  const doNext = () => {
    navigation.navigate('Tabs');

    // // 订阅成功后，显示去评价
    // const timeout = setTimeout(() => {
    //   const data = true;
    //   dispatch(setShowGoEvaluate(data));
    //   clearTimeout(timeout);
    // }, 500);
  };

  const handleClickClose = () => {
    // FirebaseEvents.general_ts_subscription_click_close_page(rountName);
    if (isIOS()) {
      console.log('start======================');
      console.log('我来了');
      console.log('end========================');
      navigation.navigate('Tabs');
    } else {
      // 防止崩溃
      navigation.dispatch(
        CommonActions.reset({
          index: 0,
          routes: [{ name: 'Tabs' }],
        }),
      );
    }
  };

  const handlePlanChange = (key: string) => {
    setSelectedPlanCode(() => key);
    dispatch(setItemPayCode(key));
  };

  // 点击订阅
  const handleClickSubscribe = async () => {
    // 上报订阅事件
    if (!payEnable) {
      return;
    }

    if (member) {
      showToast.toastWarning(t('user already subscribe'));
      return;
    }

    const prePayCallback = async () => {
      // adjust上报事件
      AdjustEventsUtil.checkout();
      // FirebaseEvents.ts_boot_page_checkout();
      // FirebaseEvents.general_ts_subscription_click_checkout(rountName);
    };
    // TODO 支付成功 setIsPaymentDone(true)
    // product ID，这里确保了只选择了一个商品，数量并且为一个
    const sku = itemPayCode;
    // handlePayment(WEEKLY_DISCOUNT_PRODUCT_ID, skus, prePayCallback);
    console.log('start======================');
    console.log('点击的code = ', sku);
    console.log('end========================');
    handlePayment(itemPayCode, [sku], prePayCallback);
  };

  // 点击恢复购买记录
  const handleRecoveryPurchaseRecord = debounce(async () => {
    if (isRestoring) {
      return;
    }

    if (member) {
      showToast.toastWarning(t('user already subscribe'));
      return;
    }

    setIsRestoring(() => true);
    try {
      Toast.show({
        type: 'tips',
        text1: t('subscription.bottom.Restoring'),
        autoHide: false,
        props: {
          _type: 'loading',
        },
      });

      const purchases = await getAvailablePurchases();

      const transactionIdList = purchases.sort((a, b) => b.transactionDate - a.transactionDate);

      const _subscriptionResult = await paymentAPI.restoreSubscription(transactionIdList[0].transactionReceipt);
      getUserMemberInfo().then((memberInfo) => {
        dispatch(setInfo(memberInfo || null));
      });
      Toast.hide();
      await new Promise((resolve) => setTimeout(resolve, 20));
      Toast.show({
        type: 'tips',
        text1: t('subscription.bottom.Restore'),
        props: {
          _type: 'success',
        },
      });
      dispatch(setIsFirstLaunch(false));
      // if (isUploadData) {

      // 查一下是否为会员
      getUserMemberInfo().then((memberInfo) => {
        dispatch(setInfo(memberInfo || null));

        if (memberInfo?.status && [3, 4, '3', '4'].includes(memberInfo.status)) {
          Toast.show({
            type: 'tips',
            text1: t('subscription.bottom.RestoreFailed'),
            props: {
              _type: 'warning',
            },
          });
        } else {
          navigation.dispatch(
            CommonActions.reset({
              index: 0,
              routes: [{ name: 'Tabs' }],
            }),
          );
        }
      });

      // } else {
      //   navigation.navigate('Basic');
      // }
    } catch (error) {
      setIsRestoring(() => false);
      console.warn(error);
      Toast.hide();
      await new Promise((resolve) => setTimeout(resolve, 20));
      Toast.show({
        type: 'tips',
        text1: t('subscription.bottom.RestoreFailed'),
        props: {
          _type: 'warning',
        },
      });
    }
  }, 500);

  useEffect(() => {
    const key = planList[1]?.code ?? '';
    setSelectedPlanCode(key);
    dispatch(setItemPayCode(key));
  }, [planList]);

  return {
    isSubscribing,
    selectedPlanCode,
    handleRecoveryPurchaseRecord,
    handleClickClose,
    handlePlanChange,
    handleClickSubscribe,
  };
};

export default useSubscribe;
